package com.hcx.poi.hssf.eventmodel;

import java.io.InputStream;

import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import com.hcx.poi.eventmodel.SheetRowHandler;

public class HSSFSheetRowParser {
	private POIFSFileSystem poifs;
	private SheetRowHandler rowHandler;

	public HSSFSheetRowParser(POIFSFileSystem poifs) {
		this.poifs = poifs;
	}

	public void addRowHandler(SheetRowHandler rowHandler) {
		this.rowHandler = rowHandler;
	}

	public void parseSheet(String sheetName) {
		InputStream din = null;
		try {
			din = poifs.createDocumentInputStream("Workbook");
			HSSFRequest req = new HSSFRequest();
			HSSFHandler handler = new HSSFHandler(sheetName);
			handler.setSheetRowHandler(rowHandler);
			req.addListenerForAllRecords(handler);
			HSSFEventFactory factory = new HSSFEventFactory();
			factory.processEvents(req, din);
		} catch (Exception ex) {
			throw new RuntimeException("文件解析异常！", ex);
		} finally {
			try {
				if (null != din) {
					din.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
}
